import { getLoginCodeAPI, userLoginAPI } from '@/api/userAPI/userAPI'
import { removeToken, setToken } from '@/utils/auth'

const actions = {
  /*
  * 获取登录验证码的action
  */
  async getLoginCodeAction(context, key) {
    const codeImage = await getLoginCodeAPI(key)
    return 'data:image/png;base64,' + btoa(new Uint8Array(codeImage).reduce((data, byte) => data + String.fromCharCode(byte), ''))
  },
  /*
  *登录的action
  */
  async userLoginAction(context, loginForm) {
    const { data } = await userLoginAPI(loginForm)
    context.commit('setUserInfo', data.user)
    context.commit('setToken', data.token.token)
  },

  /*
  *退出登录的action
  */
  userLogoutAction(context) {
    context.commit('removeToken')
  }
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}
const state = () => {
  return {
    userInfo: {},
    token: ''
  }
}

export default {
  actions,
  mutations,
  namespaced: true
}
